<?php

use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Lib\Timer;
use PHPSocketIO\SocketIO;
use Consumer\Tool;
include __DIR__ . '/vendor/autoload.php';

$task = new Worker();
// 开启多少个进程运行定时任务，注意多进程并发问题
$task->count = 32;
$task->onWorkerStart = function($task)
{
	$redis = Tool::getRedisModule();
	//用户状态推送
	Timer::add(0.1, function() {
		global $redis;
		//添加用户状态  lpush ON_LINE_USER_ID_LIST,set USER_STATUS__1 12
		while ($userid = $redis->lpop(ON_LINE_USER_ID_LIST)) {
			//用户状态
			$key = USER_STATUS . $userid;
			if (!$status = $redis->get($key)) {
				continue;
			}
			$txt = USER_ON_LINE_CONN.$userid;
			$ex = $redis->get($txt);
			$ex = explode('_',$ex);
			$event_name = $ex[0];
			$to_connection_id = $ex[1];
			$bool = Channel\Client::publish($event_name, array(
			   'to_connection_id' => $to_connection_id,
			   'content'          => $status
			));
			//关门删除与用户关联的信息
			if($bool && ($status==DOOR_CLOSED_NO || $status==DOOR_CLOSED_YES || $status==DOOR_CLOSED_YES_FAIL)){
				$redis->remove($key);
				Tool::deleteUserDoorInfo($userid);
			}
		}
	});
	//订单扣款处理
	Timer::add(0.1, function() {
        global $redis;
        while ($data = $redis->lpop(USER_ORDER_OPT_LIST)) {
           $data = explode(':',$data);
		   $class_name = "\\Consumer\\Order";
		   if (class_exists($class_name)) {
			    $data = array_merge($data,['method'=>'payOrder']);
				$class = new $class_name($data);
				$class->payOrder($data);
		   }
        }
    });
};


if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
